from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect

from django.views.decorators.csrf import csrf_protect
from django.template import Context, loader, RequestContext
from news.models import Post, Comment
from news.forms import CommentForm, PostForm
from django.contrib.auth.models import User
import datetime

#Index view.  Shows all news posts and can create new news posts
def index(request):
    latest_news_list = Post.objects.all().order_by('-posted')
    template = loader.get_template('news/index.html')
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = Post()
            post.title = form.cleaned_data['title']
            post.body = form.cleaned_data['body']
            post.author = request.user
            post.save()
            return HttpResponseRedirect('/news/')
    else:
        form = PostForm()
    data = [('latest_news_list', latest_news_list), ('postform', form),]
    context = Context(dict(data))
    a = RequestContext(request, context)
    return HttpResponse(template.render(a))

#Detail view.  Shows A specific news post and all comments on that post.
#Also allows for creation of new comments
def detail(request, post_id):
    p = get_object_or_404(Post, id=post_id)
    template = loader.get_template('news/detail.html')
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if 'edit_comment' in request.POST:
            return redirect('/news/' + post_id + '/' + request.POST['comment'])
        if form.is_valid():
            comment = Comment()
            comment.body = form.cleaned_data['body']
            comment.author = request.user
            comment.newspost = p
            comment.save()
            return HttpResponseRedirect('.')
    else:
        form = CommentForm()
    data = [('post', p), ('commentform', form),]
    context = Context(dict(data))
    a = RequestContext(request, context)
    return HttpResponse(template.render(a))
 
def edit_comment(request, post_id, comment_id):
    p = get_object_or_404(Post, id=post_id)
    q = get_object_or_404(Comment, id=comment_id)
    template = loader.get_template('news/edit_comment.html')
    if request.method == 'POST':
        if not request.user.id: return HttpResponse("Error: Must be logged in to edit comments.")
        if 'edit_comment' in request.POST:
            q.body = request.POST['new_body']
            q.editor = request.user
            q.dateEdited = datetime.datetime.now()
            q.save()
            return HttpResponseRedirect('..')
    data = [('post', p), ('comment', q),]
    context = Context(dict(data))
    a = RequestContext(request, context)
    return HttpResponse(template.render(a))